package com.study.boot.readinglist.controller;

import com.study.boot.readinglist.ReadingListRepository;
import com.study.boot.readinglist.config.AmazonProperties;
import com.study.boot.readinglist.entity.Book;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author fangdengfu
 */
@Controller
@RequestMapping("/")
public class ReadingListController {

    @Resource
    private ReadingListRepository readingListRepository;
    @Resource
    private AmazonProperties amazonProperties;

    @GetMapping(value = "/{reader}")
    public String readersBooks(@PathVariable("reader") String reader, Model model) {
        List<Book> byReader = readingListRepository.findByReader(reader);
        if (byReader != null) {
            model.addAttribute("books", byReader);
            model.addAttribute("reader", reader);
            model.addAttribute("amazonID", amazonProperties.getAssociateId());
        }
        return "readingList";
    }

    @PostMapping(value = "/{reader}")
    public String addToReadingList(@PathVariable("reader")String reader, Book book) {
        book.setReader(reader);
        readingListRepository.save(book);
        return "redirect:/{reader}";
    }

}
